package com.yanqu.road.server.manger.activity.recycle;

import com.ibm.icu.lang.UScript;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.ActivityItemRecycleData;
import com.yanqu.road.entity.activity.worldcup.UserWorldCupBallerData;
import com.yanqu.road.entity.activity.worldcup.WorldCupConfig;
import com.yanqu.road.entity.activity.worldcup.WorldCupPlayerConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.logic.bussiness.player.WorldCupActivityBussiness;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombModule;
import com.yanqu.road.server.gameplayer.module.activity.tomb.business.TombGameBusiness;
import com.yanqu.road.server.gameplayer.module.activity.tomb.entity.DbTombInfo;
import com.yanqu.road.server.gameplayer.module.activity.worldcup.WorldCupModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.worldcup.WorldCupMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WorldCupRecycleStrategy extends AbstractItemRecycleStrategy {
    @Override
    public void markNeedRecycleItem() {
        WorldCupConfig config = WorldCupMgr.getConfig();
        if (config != null) {

            ActivityInfo activityInfo = config.getActivityInfo();
            if (activityInfo != null) {
                config.getBallerConfig();
                List<String> ballerNames = new ArrayList<>();
                for (WorldCupPlayerConfig ballerConfig : config.getBallerConfig().values()) {
                    ballerNames.add(String.valueOf(ballerConfig.getQuality()));
                    ballerNames.add(ballerConfig.getName());
                }
                //球服
                addRecycleItemDataEndTime(activityInfo, config.getBallUniformItemId(), config.getScoreItemId(), ballerNames);
            }
        }
    }

    private void addRecycleItemDataEndTime(ActivityInfo activityInfo, int itemId, int scoreId, List<String> ballerNames) {
        List<String> paramList = new ArrayList<>();
        long recycleTime = activityInfo.getEndTime() * 1000L + 600 * 1000;
        paramList.add(String.valueOf(itemId));
        paramList.add(String.valueOf(scoreId));
        paramList.add("0");//转换积分值，在t_s_goods_channel表的params的位置
        paramList.add(activityInfo.getActivityName());
        //后面的参数item2score不用
        paramList.add(activityInfo.getServerListStr());
        paramList.add(String.valueOf(activityInfo.getActivityId()));
        for (String ballerName : ballerNames) {
            paramList.add(ballerName);
        }
        ActivityItemRecycleMgr.addRecycleItemData(itemId, activityType, 1, recycleTime, paramList);
    }

    @Override
    protected void initActivityType() {
        activityType = eActivityType.WorldCup.getValue();
    }

    @Override
    protected void doRecycle(long userId, ActivityItemRecycleData data) {
        if (Integer.valueOf(data.getParamList().get(1)) != 0) {
            item2Score(userId, data);

            try {
                sendNotEntryBaller(userId, data);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            removeItem(userId, data);
        }
    }


    private void removeItem(long userId, ActivityItemRecycleData data) {
        int itemId = data.getItemId();
        UserBagItem userBagItem = getUserBagItem(userId, itemId);
        if (userBagItem == null || userBagItem.getNum() <= 0) {
            return;
        }
        removeItem(userBagItem);
    }

    @Override
    public boolean isActivityRunning() {
        return false;
    }


    /**
     * 玩家未参赛的球员转换为积分
     *
     * @param userId
     * @param data
     */

    private void sendNotEntryBaller(long userId, ActivityItemRecycleData data) {
        String s = data.getParamList().get(5);
        int acitvityId = Integer.parseInt(s);
        if (acitvityId == 0) {
            return;
        }

        List<UserWorldCupBallerData> ballers;
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (null != player) {
            ballers = player.getModule(WorldCupModule.class).getBallerList();
        } else {
            ballers = WorldCupActivityBussiness.getUserWorldCupBallerData(userId, acitvityId);
        }

        if (ballers.isEmpty()) {
            return;
        }

        int scoreItemId = Integer.parseInt(data.getParamList().get(1));
        GoodsInfo toGoodsInfo = GoodsMgr.getGoodsById(scoreItemId);
        String language = UserMgr.getLanguage(userId);
        String toName = ServerLanguageMgr.getContent(toGoodsInfo.getGoodsName(), language);

        String activityName = data.getParamList().get(3);
        String serverListStr = data.getParamList().get(4);

        //球员品质对应数量
        Map<Integer, Integer> qualityAmount = new HashMap<>();

        long nowTime = DateHelper.getCurrentTime();
        Property property = new Property();
        BigInteger scoreAmount = BigInteger.valueOf(0);
        for (UserWorldCupBallerData ballerData : ballers) {
            scoreAmount = scoreAmount.add(BigInteger.valueOf(ballerData.getAbility()));

            ballerData.setRecycleTime(nowTime);
            ballerData.setUpdateOption();
            int amount = 0;
            if (qualityAmount.containsKey(ballerData.getQuality())) {
                amount = qualityAmount.get(ballerData.getQuality());
            }
            qualityAmount.put(ballerData.getQuality(), amount + 1);
        }

        property.addProperty(scoreItemId, scoreAmount);


        if (property.getGoods().size() > 0) {
            if (activityName.length() > 0) {
                activityName = ServerLanguageMgr.getContent(activityName, language);
            }
            log.info("userId : {} 汴梁世界杯未参赛球员转化为活动积分{}", userId, PropertyHelper.parsePropertyToString(property));
            String mailTitle = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.WORLDCUP_ACTIVITY_AUTO_REWARD_TITLE, language), activityName);
            // 汴梁世界杯未参赛球员转积分  亲爱的掌柜，由于您在{0}活动中，{1}×{2}、{3}×{4}、{5}×{6}、{7}×{8}未及时参赛，现已为您自动转换为{9}，敬请查收！
            int attrSize = (data.getParamList().size() - 6) + 2;//球员名字x数量 加上 活动名字，积分道具名
            Object[] paramArr = new Object[attrSize];
            int idx = 0;
            paramArr[idx++] = activityName;
            for (int i = 6; i + 1 < data.getParamList().size(); i += 2) {
                int quality = Integer.parseInt(data.getParamList().get(i));
                String ballerName = data.getParamList().get(i + 1);
                paramArr[idx++] = ServerLanguageMgr.getContent(ballerName, language);

                int count = 0;
                if (qualityAmount.containsKey(quality)) {
                    count = qualityAmount.get(quality);
                }
                paramArr[idx++] = count;
            }
            paramArr[idx++] = toName;

            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.WORLDCUP_ACTIVITY_AUTO_REWARD_CONTENT,
                    language), paramArr);
            MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(property), mailContent, mailTitle, acitvityId, serverListStr);
        }
        if (player != null) {
            player.getModule(WorldCupModule.class).setRecycleBallers(ballers);
        } else {
            WorldCupActivityBussiness.updateUserWorldCupBallerDataRecycleTime(ballers);
        }
    }
}
